<template>
  <div class="app-container">
<!--
    <div class="action-container">
      <el-button type="primary" @click="handleCreateSysUser">增加<i class="el-icon&#45;&#45;right"></i></el-button>
    </div>
-->
    <div class="filter-container">
      <el-select @change='handleFilter' style="width: 120px" class="filter-item" v-model="listQuery.f_eq_roleId" placeholder="角色">
        <el-option label="所有角色" value=""></el-option>
        <el-option v-for="item in roleList" :key="item.id" :label="item.comment" :value="item.id">
        </el-option>
      </el-select>
      <el-select style="width: 150px" class="filter-item" v-model="listQuery.f_eq_organization$parentId" placeholder="一级部门" @change='onOrgListChanged'>
        <el-option label="全部(一级部门）" value=""></el-option>
        <el-option v-for="item in orgList" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="listQuery.f_eq_orgId" style="width: 150px;" class="filter-item" placeholder="二级部门" @change="handleFilter">
        <el-option label="全部(二级部门）" value="" />
        <el-option v-for="item in orgList2" :key="item.id" :label="item.name" :value="item.id"></el-option>
      </el-select>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="姓名" v-model="listQuery.f_lk_name"></el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="账号" v-model="listQuery.f_lk_username"></el-input>
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>

    <el-table :data="list" v-loading.body="listLoading" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column align="center" label='ID' width="80">
        <template slot-scope="scope">
          {{scope.row.id}}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="150">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column label='账号' width="200">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label='手机号码'>
        <template slot-scope="scope">
          {{scope.row.phone}}
        </template>
      </el-table-column>
      <el-table-column label="角色" align="left">
        <template slot-scope="scope">
          {{(scope.row.role || {}).comment}}
        </template>
      </el-table-column>
      <el-table-column label="部门" align="left">
        <template slot-scope="scope">
          {{(scope.row.organization || {}).name}}
        </template>
      </el-table-column>
      <el-table-column label="微信号"  width="100" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.openId" :src="scope.row.headImgUrl" style="width: 24px; height: 24px">
          <el-tag v-if="!scope.row.openId" type="danger">未绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label='修改时间' width="200">
        <template slot-scope="scope">
          {{scope.row.modifyTime}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320" align="left">
        <template slot-scope="scope">
          <el-button type="success" size="small" :disabled="scope.row.id === 1" @click="handleUpdateSysUser(scope.row)">修改</el-button>
          <el-button type="danger" size="small" :disabled="scope.row.id === 1" @click="handleDeleteSysUser(scope.row.id)">删除<i class="el-icon--right"></i></el-button>
          <el-button type="info" size="small" v-if="scope.row.id !== 1 && scope.row.status === 1" @click="handleDisableSysUser(scope.row.id)">禁用<i class="el-icon--right"></i></el-button>
          <el-button type="success" size="small" v-if="scope.row.id !== 1 && scope.row.status !== 1" @click="handleEnableSysUser(scope.row.id)">启用<i class="el-icon--right"></i></el-button>
          <el-button type="warning" size="small" @click="handleResetPassword(scope.row)">重置密码</el-button>
        </template>
      </el-table-column>
      <!--<el-table-column align="center" prop="created_at" label="Display_time" width="200">-->
        <!--<template slot-scope="scope">-->
          <!--<i class="el-icon-time"></i>-->
          <!--<span>{{scope.row.display_time}}</span>-->
        <!--</template>-->
      <!--</el-table-column>-->
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!--增加对话框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="sysUser" label-position="left" label-width="200px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="账号" prop="username">
          <el-input type="text" v-model="sysUser.username"  placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input type="text" v-model="sysUser.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select class="filter-item" v-model="sysUser.roleId" placeholder="请选择用户角色">
            <el-option v-for="item in roleList" :key="item.id" :label="item.comment" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="orgId">
          <div class="el-form-item__content">
            <el-select v-model="userParentId" @change='onUserParentIdChanged' placeholder="先选择一级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in orgList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
            <el-select v-model="sysUser.orgId" placeholder="再选择二级部门">
              <el-option label="请选择" :value="0" />
              <el-option v-for="item in userOrgList" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="tryCreateSysUser">确定</el-button>
        <el-button v-else type="primary" @click="tryUpdateSysUser">确定</el-button>
      </div>
    </el-dialog>

    <!--增加对话框-->
    <el-dialog title="重置密码" :visible.sync="showResetPwdDialog">
      <el-form :rules="resetPwdRules" ref="resetPwdForm" :model="sysUser" label-position="left" label-width="200px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="用户名" prop="name">
          <el-input type="text" v-model="sysUser.username" :disabled="true" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="text" v-model="sysUser.password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showResetPwdDialog = false">取消</el-button>
        <el-button type="primary" @click="tryResetPassword">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui'
import { getUserList, getByUsername, addSysUser, updateSysUser, deleteSysUser, enableSysUser, disableSysUser, updatePassword } from '@/api/user'
import { getOrgList } from '@/api/org'
import { getRoleList } from '@/api/role'

export default {
  data() {
    const validateSysUsername = (rule, value, callback) => {
      if (getByUsername(value) !== undefined) {
        callback(new Error('用户名已经存在'))
      } else {
        callback()
      }
    }

    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_eq_roleId: '',
        f_eq_organization$parentId: '',
        f_eq_orgId: '',
        f_lk_username: undefined,
        f_lk_name: undefined,
        sort: '+id'
      },
      roleList: [],
      orgList: [],
      orgList2: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '增加',
        update: '修改'
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空。', trigger: 'change' }, { validator: validateSysUsername, trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空。', trigger: 'change' }],
        name: [{ required: true, message: '姓名不能为空。', trigger: 'change' }],
        roleId: [{ required: true, message: '用户角色不能为空。', trigger: 'change' }]
      },
      sysUser: {
        id: 0,
        name: '',
        username: '',
        password: '',
        roleId: 2,
        orgId: 0
      },
      userParentId: 0,
      userOrgList: [],
      showResetPwdDialog: false,
      resetPwdRules: {
        password: [{ required: true, message: '密码不能为空。', trigger: 'change' }]
      }
    }
  },
  filters: {
    wxClassFilter(status) {
      return status ? 'success' : 'danger'
    },
    wxValueFilter(status) {
      return status ? '已绑定' : '未绑定'
    },
    roleFilter(role) {
      if (role) {
        return role.name
      }

      return ''
    }
  },
  created() {
    this.fetchRoleList()
    this.fetchOrgList()
    this.fetchData()
  },
  methods: {
    fetchRoleList() {
      getRoleList().then(response => {
        this.roleList = response.data
      })
    },
    fetchOrgList() {
      getOrgList({ f_eq_type: 1 }).then(response => {
        this.orgList = response.data
      })
    },
    fetchOrgList2(parentId) {
      getOrgList({ f_eq_parentId: parentId }).then(response => {
        this.orgList2 = response.data
      })
    },
    onOrgListChanged() {
      if (this.listQuery.f_eq_organization$parentId !== '') {
        this.fetchOrgList2(this.listQuery.f_eq_organization$parentId)
      } else {
        this.orgList2 = []
      }
      // 一级部门改变后，默认查询所有二级部门（不指定orgId）
      this.listQuery.f_eq_orgId = ''
      this.listQuery.page = 1
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true
      getUserList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      this.listQuery.f_lk_username = undefined
      this.listQuery.f_lk_name = undefined
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    onUserParentIdChanged() {
      getOrgList({ f_eq_parentId: this.userParentId }).then(response => {
        this.userOrgList = response.data
        // 一级部门改变后，用户部门ID默认选择第一个
        if (this.userOrgList && this.userOrgList.length > 0) {
          this.sysUser.orgId = this.userOrgList[0].id
        }
      })
    },
    handleCreateSysUser() {
      // 设置界面数据
      this.sysUser.username = undefined
      this.sysUser.name = undefined
      this.sysUser.password = undefined

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryCreateSysUser() {
      // 校验,然后执行
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const user = {}
          user.id = this.sysUser.id
          user.name = this.sysUser.name
          user.username = this.sysUser.username
          if (this.sysUser.roleId) {
            user.roleId = this.sysUser.roleId
          }
          if (this.sysUser.orgId) {
            user.orgId = this.sysUser.orgId
          }
          console.log(user)
          addSysUser(user).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleUpdateSysUser(row) {
      // 设置界面数据
      this.sysUser.id = row.id
      this.sysUser.name = row.name
      this.sysUser.username = row.username
      this.sysUser.roleId = (row.role || {}).id || 0
      this.sysUser.orgId = (row.organization || {}).id || 0

      // 根据一级部门，更新二级部门列表
      this.userParentId = (row.organization || {}).parentId || 0
      getOrgList({ f_eq_parentId: this.userParentId }).then(response => {
        this.userOrgList = response.data
      })

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryUpdateSysUser() {
      // 校验,然后执行
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const user = {}
          user.id = this.sysUser.id
          user.name = this.sysUser.name
          user.username = this.sysUser.username
          // 后台接受的是数组
          user.roleId = this.sysUser.roleId
          user.orgId = this.sysUser.orgId
          console.log(user)
          updateSysUser(user).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '修改成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleResetPassword(row) {
      // 设置界面数据
      this.sysUser.id = row.id
      this.sysUser.username = row.username
      this.sysUser.name = row.name
      this.sysUser.password = undefined

      // 显示界面
      this.showResetPwdDialog = true
      this.$nextTick(() => {
        this.$refs['resetPwdForm'].clearValidate()
      })
    },
    tryResetPassword() {
      //校验,然后执行
      this.$refs['resetPwdForm'].validate(valid => {
        if (valid) {
          var user = {}
          user.id = this.sysUser.id
          user.password = this.sysUser.password

          updatePassword(user).then(() => {
            this.showResetPwdDialog = false
            this.$notify({ title: '成功', message: '操作成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleDeleteSysUser(id) {
      if (id === 1) {
        MessageBox.alert('不能删除系统管理员')
        return
      }

      MessageBox.confirm('请确认是否要删除该用户？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          deleteSysUser(id).then(() => {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {})
    },
    handleDisableSysUser(id) {
      if (id === 1) {
        MessageBox.alert('不能禁用系统管理员')
        return
      }

      MessageBox.confirm('请确认是否要禁用该用户？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          disableSysUser(id).then(() => {
            this.$notify({ title: '成功', message: '禁用成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {})
    },
    handleEnableSysUser(id) {
      if (id === 1) {
        MessageBox.alert('不能对系统管理员进行该操作')
        return
      }

      MessageBox.confirm('请确认是否要启用该用户？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          enableSysUser(id).then(() => {
            this.$notify({ title: '成功', message: '启用成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {})
    }
  }
}
</script>

<style lang="scss" scoped>
  // 将两个选择框水平显示
  .el-form-item__content {
    width: 500px;
    display: flow;
  }
</style>
